/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkSipTcpSession.h"
#include "MkSipMessage.h"
#include "MkSipTcpListener.h"
#include "MkUtil/MkLog.h"

CMkSipTcpSession::CMkSipTcpSession(CMkEvent* pEvent, CMkTimer* pTimer, CMkTcpServer* pServer)
    :CMkTcpSession(pEvent, pTimer, pServer)
    , m_MaxRecvLen(LenHalfM)
    , m_pRecvBuffer((Uint8*)malloc(LenHalfM))
    , m_nOffsetLen(0)
{
    memset(m_pRecvBuffer, 0, LenHalfM);
}

Uint32 CMkSipTcpSession::OnRecv()
{
    Uint32 nToReadLen = m_MaxRecvLen - m_nOffsetLen;
    if (0 == nToReadLen) {
        MkErrorLog("buffer size:%d not parse success\n", m_MaxRecvLen);
        Close();
        return UnknownError;
    }
    Uint32 ErrorCode = Recv(m_pRecvBuffer + m_nOffsetLen, nToReadLen);
    MkCheckErrorLog(ErrorCode, "sip tcp session recv failed\n");
    CMkSipTcpListener* pListener = dynamic_cast<CMkSipTcpListener*>(GetParentServer());
    //not listener only recv
    if (!pListener) {
        return NoneError;
    }
    m_nOffsetLen += nToReadLen;
    Uint32 nUsed = 0;
    ErrorCode = pListener->OnSipRecved(m_pRecvBuffer, m_nOffsetLen, GetRemoteHost(), GetRemotePort(), GetLocalHost(), GetLocalPort(), nUsed);
    if (NoneError != ErrorCode) {
        Close();
        return NoneError;
    }

    m_nOffsetLen -= nUsed;
    memmove(m_pRecvBuffer, m_pRecvBuffer + nUsed, m_nOffsetLen);
    return NoneError;
}

CMkSipTcpSession::~CMkSipTcpSession()
{
    MkFree(m_pRecvBuffer);
}
